package com.devframe.web.loader;

import javax.servlet.ServletContext;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.web.context.ServletContextAware;

import com.devframe.sys.loader.AbstractSysLoader;
import com.devframe.web.util.common.ServerDetector;

/**
 * 
 * @author 詹保山(softzbs@126.com)
 * @desc: 获取上下文信息的类
 * Jul 9, 2010
 */
public class MyWebContextLoader extends AbstractSysLoader implements ServletContextAware{
	private static Logger logger = Logger.getLogger(MyWebContextLoader.class);
	private ServletContext servletContext;
	private static ContextHelper helper = new ContextHelper();
	private static MyWebContextLoader instance;
	/**
	 * 模板文件位置
	 */
	private String templatePath;
	/**
	 * jsp页面跟路径
	 */
	private String pageRootPath="/";
	/**
	 * 系统包名的前缀
	 */
	private String packageNamePrefix;
	
	private MyWebContextLoader() {}
	private static class ContextHelper  {
		public Object getBean(String beanName) {
			return MyWebContextLoader.instance.accessApplicationContext().getBean(beanName);
		}
		public String getRealPath(String path){
			return  MyWebContextLoader.instance.servletContext.getRealPath(path);
		}
		public String getContextPath(){
			return  MyWebContextLoader.instance.servletContext.getServletContextName();
		}
		public ServletContext getServletContext(){
			return MyWebContextLoader.instance.servletContext;
		}
	}
	private static MyWebContextLoader factoryMethod() {
		logger.info("初始化base dev 上下文");
		instance = new MyWebContextLoader();
		return instance;
	}
	/**
	 * 
	 * Aug 28, 2011<br/>
	 * @描述：获取当前实例
	 * <br/> 
	 * @return
	 */
	public static MyWebContextLoader getInstance(){
		return MyWebContextLoader.instance;
	}
	/**
	 * 得到Web上下文的ServletContext
	 * @return
	 * @author:詹保山softzbs@126.com
	 */
	public  ServletContext getServletContext(){
		return helper.getServletContext();
	}

    /**
     * 获得上下文的路径
     * @return
     * @author:詹保山softzbs@126.com
     */
	public  String getContextPath(){
		return helper.getContextPath();
	}
	/**
	 * 根据文件名获得实际的路径
	 * @param path
	 * @return
	 * @author:詹保山softzbs@126.com
	 */
	public  String getRealPath(String path){
		return helper.getRealPath(path);
	}
	public void init(){
		 logger.info("开始系统初始化...\n");
	        logger.info(System.getProperty("contextConfigLocation"));
	        //设置日志输出变量，以便LOG4J输入日志文件都在logs下
	        if(ServerDetector.isTomcat()){
	            System.setProperty("MY_LOG_ROOT", "${catalina.home}/logs");
	        } else if(ServerDetector.isWebSphere()){
	            System.setProperty("MY_LOG_ROOT", "${USER_INSTALL_ROOT}/logs");
	        } else {
	            //TODO 其他中间件的日志位置
	            System.setProperty("MY_LOG_ROOT", ".");
	        }
	        // 启动其他相关服务
	        otherInit();
	        logger.info("系统初始化完毕。\n");
	    }
	    /**
	     * 定义了一个空操作的方法，继承的类覆盖该方法，完成其他的初始化操作。
	     */
	    protected void otherInit() {
	    }
	    /**
	     * 获取WebRoot的文件目录路径，以/结尾
	     * @return 绝对路径
	     */
	    public String getRootPath() {
	        try {
	        	//String rootPath = request.getSession().getServletContext().getRealPath("/");
	        	String rootPath = this.getServletContext().getRealPath("/");
	        	rootPath = rootPath.replaceAll("\\\\", "/");
	        	rootPath += "/";
	            return rootPath;
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return null;
	    }
	public void setServletContext(ServletContext servletContext) {
		logger.info("初始化Base Dev Framework上下文...ServletContext="+servletContext);
		this.servletContext = servletContext;
		/**初始化上下文*/
		if(this.servletContext!=null){
			//init();
		}
	}
	
	/**
	 * 根据BeanName的名称获得 BEAN实体
	 * @param beanName bean的名称
	 * @return 
	 * @author:詹保山softzbs@126.com
	 */
	public Object getBean(String beanName) {
		return  super.accessApplicationContext().getBean(beanName);
	}

	/**
	 * reload
	 * 重新初始化spring上下文
	 */
	public void reload() {
	    ((AbstractApplicationContext)  super.accessApplicationContext()).close();
		((AbstractApplicationContext)  super.accessApplicationContext()).refresh();
	}

	/**
	 * 自动装配一个Bean对象
	 * autowireComponent
	 * @param bean
	 *            bean
	 */
	public void autowireComponent(Object bean) {
		((AbstractApplicationContext)  super.accessApplicationContext()).getBeanFactory().autowireBeanProperties(bean,
				AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
	}
	/**
	 * 关闭Spring上下文
	 * close
	 * 
	 */
	public void close() {
		((AbstractApplicationContext) super.accessApplicationContext()).close();
	}
	public String getTemplatePath() {
		return templatePath;
	}
	public void setTemplatePath(String templatePath) {
		this.templatePath = templatePath;
	}
	public String getPageRootPath() {
		return pageRootPath;
	}
	public void setPageRootPath(String pageRootPath) {
		this.pageRootPath = pageRootPath;
	}
	public String getPackageNamePrefix() {
		return packageNamePrefix;
	}
	public void setPackageNamePrefix(String packageNamePrefix) {
		this.packageNamePrefix = packageNamePrefix;
	}
}
